package com.github.codemperor.core.message.dingtalk.robot.base;

import com.alibaba.fastjson.JSONObject;
import com.github.codemperor.core.logger.DefaultLogger;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class MsgQueue {
    private static DefaultLogger log = DefaultLogger.logger(MsgQueue.class);

    /**
     * 是否开始执行消费
     */
    private static boolean isProcessing = false;

    /**
     * 队列长度
     */
    private static final int queueSize = 10000;
    /**
     * 消息队列
     */
    private static BlockingQueue<Object> msgQueue = new LinkedBlockingQueue<>(queueSize);

    /**
     * 消费者
     */
    public static void customer() {
        if (isProcessing) {
            log.warn("[MsgQueue customer] customer is already begin, queue size: {}", msgQueue.size());
            return;
        }
        isProcessing = true;

        Thread msgQueueThread = new Thread(() -> {
            log.info("[MsgQueue customer] customer start!!!!");
            RestTemplate restTemplate = new RestTemplate();
            while (true) {
                try {
                    Object msgRequest = msgQueue.take();
                    log.info("[sendDingtalkRobotMarkdownMsg] request: {}, queue size: {}", msgRequest, msgQueue.size());
                    Object object = restTemplate.postForEntity(BaseDingRobot.dingtalkRobotUrl, msgRequest, Object.class);
                    log.info("[sendDingtalkRobotMarkdownMsg] res: {}", JSONObject.toJSONString(object));
                } catch (InterruptedException e) {
                    log.error("", e);
                }

                try {
                    Thread.sleep(5100);
                } catch (InterruptedException e) {
                    log.error("", e);
                }
            }
        });
        msgQueueThread.setName("dingtalk-robot-msg-queue");
        msgQueueThread.setDaemon(true);
        msgQueueThread.start();
    }

    /**
     * 队列存放
     *
     * @param o
     */
    public static void setQueue(Object o) {
        try {
            boolean isOk = msgQueue.offer(o);
            if (!isOk) { //如果添加元素失败，则移除头部元素并尝试再一次添加，这里不做retry
                msgQueue.poll();
                msgQueue.offer(o);
            }
        } catch (Exception e) {
            log.error("", e);
        }
    }
}
